package com.tudouji.framework.security.service;

import javax.annotation.Resource;

import com.tudouji.common.constant.HttpStatus;
import com.tudouji.common.enums.UserStatus;
import com.tudouji.common.exception.ApplicationException;
import com.tudouji.common.exception.BaseException;
import com.tudouji.common.utils.*;
import com.tudouji.common.utils.http.HttpUtils;
import com.tudouji.common.utils.ip.IpUtils;
import com.tudouji.common.utils.sign.Md5Utils;
import com.tudouji.framework.config.EncrypAES;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.domain.Tuser;
import com.tudouji.project.system.service.ISysUserService;
import com.tudouji.project.system.service.ITuserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.tudouji.common.constant.Constants;
import com.tudouji.common.exception.CustomException;
import com.tudouji.common.exception.user.CaptchaException;
import com.tudouji.common.exception.user.CaptchaExpireException;
import com.tudouji.common.exception.user.UserPasswordNotMatchException;
import com.tudouji.framework.manager.AsyncManager;
import com.tudouji.framework.manager.factory.AsyncFactory;
import com.tudouji.framework.redis.RedisCache;
import com.tudouji.framework.security.LoginUser;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{

    private static final Logger log = LoggerFactory.getLogger(SysLoginService.class);


    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ITuserService tuserService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        Tuser tuser = tuserService.selectTuserByName(loginUser.getUser().getPhonenumber());
        if (tuser != null){
            loginUser.getUser().setTuserId(tuser.getGuid());
        }

        recordLoginInfo(loginUser.getUser());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 土豆老后台登录-货运单、采收付款单
     */
    /*public void loginOldSys(SysUser user)
    {
        String loginname = user.getUserName();
        String password = EncrypAES.decrypt(user.getPassword());
        String result = HttpUtils.sendGet("http://127.0.0.1:8091/weixin/WechatLogin!login.action", "loginname=" + loginname +
                "&password=" + password);
        log.info("老系统登录返回：" + result);
    }*/

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUser user)
    {
        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(user);
    }
    /**
     * 登录验证-不要验证码
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String loginNoVerifyKey(String username, String password)
    {
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        Tuser tuser = tuserService.selectTuserByName(loginUser.getUser().getPhonenumber());
        if (tuser != null){
            loginUser.getUser().setTuserId(tuser.getGuid());
        }

        recordLoginInfo(loginUser.getUser());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public LoginUser createLoginUser(SysUser user){
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setPermissions(permissionService.getMenuPermission(user));
        return loginUser;
    }

    //校验初始密码是否已修改
    public void checkPwd(SysUser user, String password){
        if (user != null && !user.getUserType().equals("00") && "123456".equals(password)){
            throw new CustomException("请修改初始密码", HttpStatus.MODIFY_PWD);
        }
    }
}
